package com.example.nbshangpping.login;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.example.nbshangpping.ChangeHeadDialog;
import com.example.nbshangpping.R;
import com.example.nbshangpping.utils.BaseActivity;
import com.example.nbshangpping.utils.EditUserDialog;
import com.example.nbshangpping.utils.SaveUserUtils;
import com.example.nbshangpping.utils.URLUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/* 个人中心*/
public class PersonCenterActivity extends BaseActivity {

    private UserBean.DataBean userInfo;  //之前登录时保存的用户信息
    ImageView headIv,backIv,nicknameIv,nameIv,addressIv;
    TextView nicknameTv,nameTv,addressTv,telTv,saveTv,changeTv;
    UserBean.DataBean newuserInfo;   //保存之后的对象信息
    String imgpath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_center);
        userInfo = SaveUserUtils.getUserInfo(this); //获取到保存的登录信息
        newuserInfo = new UserBean.DataBean(userInfo.getId(),userInfo.getPhone(),userInfo.getPassword(),
                userInfo.getName(),userInfo.getAddress(),userInfo.getNickname(),userInfo.getQuestion(),
                userInfo.getAnswer());
        //保存文件的路径
        imgpath = URLUtils.getImgPath(this,userInfo.getPhone());
        initView();
        setListener();
        setView();
    }
    // 设置登录显示在view上
    private void setView() {
        nicknameTv.setText(userInfo.getNickname());
        nameTv.setText(userInfo.getName());
        telTv.setText(userInfo.getPhone());
        addressTv.setText(userInfo.getAddress());
        // 显示头像
        File file = new File(imgpath);
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imgpath);
            headIv.setImageBitmap(bitmap);
        }else{
            headIv.setImageResource(R.mipmap.icon);
        }
    }

    private void setListener() {
        headIv.setOnClickListener(listener);
        backIv.setOnClickListener(listener);
        nicknameIv.setOnClickListener(listener);
        nameIv.setOnClickListener(listener);
        addressIv.setOnClickListener(listener);
        saveTv.setOnClickListener(listener);
        changeTv.setOnClickListener(listener1);
    }
    View.OnClickListener listener1=new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(PersonCenterActivity.this, PwdQuestionActivity.class);
            startActivity(intent);
        }
    };
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.center_iv_back:  //返回
                    if (isSameObj()) {
                        finish();
                    }else {
                        showBackDialog();
                    }
                    break;
                case R.id.center_iv_head:  //头像
                    showChangeheadDialog();
                    break;
                case R.id.center_iv_nickname:  //昵称
                    String hint ="请输入修改的贝壳昵称:";
                    showEditUserDialog(hint,nicknameTv);
                    break;
                case R.id.center_iv_address:  //地址
                    hint = "请输入修改的收货地址:";
                    showEditUserDialog(hint,addressTv);
                    break;
                case R.id.center_iv_name:  // 姓名
                    hint = "请输入修改的收货姓名:";
                    showEditUserDialog(hint,nameTv);
                    break;
                case R.id.center_tv_save:  //保存
                    // 如果内容改变了，那么就完善个人信息，如果内容没有改变，不用联网，修改用户信息了
                    boolean isSameObj = isSameObj();
                    if (isSameObj) {
                        Toast.makeText(PersonCenterActivity.this,"已保存最新内容！",Toast.LENGTH_SHORT).show();
                    }else {
                        Map<String,String>map = new HashMap<>();
                        map.put("id",newuserInfo.getId()+"");
                        map.put("address",newuserInfo.getAddress());
                        map.put("nickname",newuserInfo.getNickname());
                        map.put("name",newuserInfo.getName());
                        postNetwork(URLUtils.updateinfo_url,map);
                    }
                    break;
            }
        }
    };
    // 显示对话框
    private void showChangeheadDialog() {
        ChangeHeadDialog headDialog = new ChangeHeadDialog(this);
        headDialog.show();
        headDialog.setDialogWidth();
        headDialog.setOnChangeheadListener(new ChangeHeadDialog.OnChangeheadListener() {
            @Override
            public void clickCamear() {   //跳转到照相机页面
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,100);
            }
            @Override
            public void clickLocal() {   //跳转到本地图片页面
                Intent intent = new Intent(PersonCenterActivity.this,LocalImgActivity.class);
                startActivityForResult(intent,200);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode==100) {
            Bundle bundle = data.getExtras();
            Bitmap bm = (Bitmap) bundle.get("data");
            headIv.setImageBitmap(bm);
            saveBitmap(bm);
        }
        if (requestCode == 200 && resultCode== Activity.RESULT_OK) {
            String fpath = data.getStringExtra("fpath");
            Bitmap bitmap = BitmapFactory.decodeFile(fpath);
            headIv.setImageBitmap(bitmap);
            saveBitmap(bitmap);
        }
    }
    //  将图片保存起来
    private void saveBitmap(Bitmap bm) {
        try {
            FileOutputStream fos = new FileOutputStream(imgpath);
            bm.compress(Bitmap.CompressFormat.JPEG,80,fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 弹出返回对话框：内容改变了，但是没保存
    private void showBackDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息");
        builder.setMessage("当前页面数据有改变,且未保存，是否仍要返回上级页面？");
        builder.setIcon(R.mipmap.icon);
        builder.setPositiveButton("取消",null);
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();//结束当前页面
            }
        });
        builder.create().show();
    }

    @Override
    public void onSuccess(String result) {
        super.onSuccess(result);
        UserBean jsonbean = new Gson().fromJson(result, UserBean.class);
        switch (jsonbean.getCode()) {
            case 200:
                SaveUserUtils.saveUserToFile(this,newuserInfo);
                userInfo = SaveUserUtils.getUserInfo(this);
                Toast.makeText(PersonCenterActivity.this,"更新内容成功！",Toast.LENGTH_SHORT).show();
                break;
            default:
                Toast.makeText(PersonCenterActivity.this,"更新内容失败！",Toast.LENGTH_SHORT).show();
                break;
        }
    }

    // 判断是否数据改变了
    private boolean isSameObj() {
        String nn = nicknameTv.getText().toString().trim();
        String ad = addressTv.getText().toString().trim();
        String name = nameTv.getText().toString().trim();
        newuserInfo.setAddress(ad);
        newuserInfo.setNickname(nn);
        newuserInfo.setName(name);
        return  newuserInfo.equals(userInfo);
    }

    private void showEditUserDialog(String hint,TextView tv) {
//        1.创建对话框对象
        EditUserDialog dialog = new EditUserDialog(this);
//        2.显示对话框
        dialog.show();
//        3.设置参数
        dialog.setDialogWidth();
        dialog.setTipHint(hint);
        dialog.setOnEnsureListener(new EditUserDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String msg) {
                tv.setText(msg);
                dialog.cancel();
            }
        });
    }

    private void initView() {
        headIv = findViewById(R.id.center_iv_head);
        backIv = findViewById(R.id.center_iv_back);
        nicknameIv = findViewById(R.id.center_iv_nickname);
        nameIv = findViewById(R.id.center_iv_name);
        addressIv = findViewById(R.id.center_iv_address);
        nicknameTv = findViewById(R.id.center_tv_nickname);
        nameTv = findViewById(R.id.center_tv_name);
        addressTv = findViewById(R.id.center_tv_address);
        telTv = findViewById(R.id.center_tv_tel);
        saveTv = findViewById(R.id.center_tv_save);
        changeTv=findViewById(R.id.frag_center_tv);
    }
}
